import React, { Component } from 'react'
import axios from 'axios'
import { Notify } from 'react-vant';
import '../login.css';
export default class Login extends Component {
    state = {
        username: '',
        password: '',
    }

    username(e) {
        this.setState({
            username: e.target.value,
        });
    }
    password(e) {
        this.setState({
            password: e.target.value,
        });
    }
    //登录
    tohome = () => {
        axios({
            url: '/api/login',
            method: 'post',
            data: {
                username: this.state.username,
                password: this.state.password
            }
        }).then(res => {
            console.log(res);
            if (res.data.code === 1) {
                window.localStorage.setItem('token', res.data.token)
                console.log(res.data.token);
                localStorage.setItem('token', res.data.token)
                localStorage.setItem('username', res.data.data.username)
                localStorage.setItem('img', res.data.data.img)
                
                this.props.history.push('/main/my')
                //同步姓名和头像   登录 后 我的  订单  有没？没
            
                
                Notify.show({ type: 'success', message: res.data.msg });




            } else {
                Notify.show({ type: 'danger', message: res.data.msg });
            }
        })
    }
    //取消
    save = () => {
        this.props.history.push('/main/my')
    }
    //注册
    register = () => {
        axios({
            url: '/api/register',
            method: 'post',
            data: {
                username: this.state.username,
                password: this.state.password,
            }
        }).then(res => {
            if (res.data.code === 2) {
                Notify.show({ type: 'warning', message: res.data.msg });
            } else {
                Notify.show({ type: 'success', message: res.data.msg })
            }
        })
    }

    render() {
        return (
            <div className="public1">
                <header onClick={() => { this.save() }}>取消</header>
                <div className='login'>
                    <h2>登录美洽医疗</h2>
                    <p>
                        <label>用户名: </label>
                        <input type="text" placeholder="请输入用户名" onChange={(e) => { this.username(e) }} />
                    </p>
                    <p>
                        <label>密&nbsp;&nbsp;&nbsp;&nbsp;码: </label>
                        <input type="password" placeholder="请输入密码" onChange={(e) => { this.password(e) }} />
                    </p>
                    <button onClick={() => { this.tohome() }}>登录</button>
                    <button onClick={() => { this.register() }}>注册</button>
                </div>
            </div>
        )
    }
}